using IQIGame.Onigao.Framework;
using System;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace IQIGame.Onigao.Game.Editors
{
    public class MediaBuildProcessor
    {

        [MenuItem("GameEditor/BuildTools/Coyp Media Files To Streaming", priority = 1)]
        public static void CopyMediaToStreamingAssets()
        {
            CopyMedia();
            AssetDatabase.Refresh();
        }

        [MenuItem("GameEditor/BuildTools/Delete All  Media Files", priority = 1000)]
        public static void DeleteMediaFromStreamingAssets()
        {
            DeleteBuildInMedia();
            AssetDatabase.Refresh();
        }

        #region 媒体文件

        static readonly string DefaultMediaPath = Path.Combine(Application.dataPath, FrameworkPath.MediaPath);
        static string destinationMediaFolder = string.Empty;
        public static readonly string DefaultBuildInMefiaFolder = Path.Combine(Application.streamingAssetsPath, FrameworkPath.PackedMediaPath);
        static MediaConfig mediaConfig;
        //static Regex cullBuildLangRegex; //要剔除的语言
        //static Regex curBuildLangRegex; //当前的语言

        /// <summary>
        /// 拷贝媒体资源
        /// </summary>
        /// <param name="targetMediaPath">不存在时则拷贝到streamingAssetsPath</param>
        public static bool CopyMedia(string targetMediaPath = null)
        {
            //cullBuildLangRegex = ABBuildCreator.GetBuildLangRegex(buildLanguage);
            //curBuildLangRegex = new Regex(buildLanguage.ToString(), RegexOptions.IgnoreCase);

            //if (OverseasCullingConfig.IsEnableOverseasCulling)
            //{
            //    OverseasCullingPathTrieTree = OverseasCullingConfig.GlobalOverseasCullingConfig?.GetOverseasCullingAssetPathsTree();
            //}
            //else
            //{
            //    OverseasCullingPathTrieTree = null;
            //}
            //存awb文件
            mediaConfig = new MediaConfig();

            if (string.IsNullOrEmpty(targetMediaPath))
                destinationMediaFolder = DefaultBuildInMefiaFolder;
            else
                destinationMediaFolder = targetMediaPath;

            if (Directory.Exists(destinationMediaFolder))
                FilePathHelper.DeleteDir(destinationMediaFolder);

            if (DirectoryCopy(DefaultMediaPath, destinationMediaFolder, true, OnCopyMediaFile, OnPreCopyCheck))
            {
                //写入awb文的 json
                try
                {
                    //if (destinationMediaFolder.StartsWith(Application.streamingAssetsPath)) //只有包内的需要
                    {
                        var json = Newtonsoft.Json.JsonConvert.SerializeObject(mediaConfig);
                        var jsonPath = Path.Combine(destinationMediaFolder, FrameworkPath.PackedMediaConfigJsonFileName);
                        File.WriteAllText(jsonPath, json);
                        Debug.Log($"Write mediaConfig json complete, awbFileNum:{mediaConfig.awbFileHashSet.Count}.");
                    }
                    return true;
                }
                catch (Exception e)
                {
                    Debug.LogError($"Write mediaConfig json error:{e}");
                }
            }
            else
            {

                Debug.LogError("CopyMedia : Could not copy media folder");
            }

            destinationMediaFolder = null;

            return false;
        }

        public delegate bool CopyFileFilter(FileInfo file);

        public static bool DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs, Action<FileInfo> afterCopyFileAction = null, CopyFileFilter copyFileFilter = null)
        {
            // Get the subdirectories for the specified directory.
            var dir = new DirectoryInfo(sourceDirName);

            if (!dir.Exists)
            {
                Debug.LogError("Source directory doesn't exist");
                return false;
            }

            var dirs = dir.GetDirectories();

            // If the destination directory doesn't exist, create it. 
            if (!Directory.Exists(destDirName))
                Directory.CreateDirectory(destDirName);

            // Get the files in the directory and copy them to the new location.
            var files = dir.GetFiles();
            foreach (var file in files)
            {
                if (copyFileFilter == null || copyFileFilter.Invoke(file))
                {
                    var tempPath = Path.Combine(destDirName, file.Name);
                    var newFile = file.CopyTo(tempPath, true);
                    afterCopyFileAction?.Invoke(newFile);
                }
            }

            // If copying subdirectories, copy them and their contents to new location. 
            if (copySubDirs)
            {
                foreach (var subDir in dirs)
                {
                    var tempPath = Path.Combine(destDirName, subDir.Name);
                    DirectoryCopy(subDir.FullName, tempPath, true, afterCopyFileAction, copyFileFilter);
                }
            }

            return true;
        }

        static bool OnPreCopyCheck(FileInfo file)
        {
            if (file.Extension.Equals(".meta"))
                return false; //剔除meta

            //if (file.Extension.Equals(PathConsts.VideoExtension))
            //{
            //    //视频文件多语言剔除
            //    if (cullBuildLangRegex.IsMatch(file.Name))
            //    {
            //        //Debug.Log($"Cull video file : {file.FullName}");
            //        return false; //其他语言的进行剔除
            //    }
            //    else if (!curBuildLangRegex.IsMatch(file.Name)) //非当前语言的，即不带语言类型(如EN_US)的文件
            //    {
            //        var fileLangName = string.Concat(Path.GetFileNameWithoutExtension(file.Name), "_", buildLanguage.ToString(), PathConsts.VideoExtension);
            //        var fileLangPath = Path.Combine(file.DirectoryName, fileLangName);
            //        if (File.Exists(fileLangPath))
            //        {
            //            //Debug.Log($"Cull video file : {file.FullName}");
            //            return false; //存在当前语言的文件，需要剔除默认的视频文件
            //        }
            //    }
            //}

            return true;
        }

        static void OnCopyMediaFile(FileInfo newFile)
        {
            if (newFile.Extension.ToLower().Equals(FrameworkPath.AudioAwbExtension))
            {
                var fileName = Path.GetFileNameWithoutExtension(newFile.Name);
                mediaConfig.awbFileHashSet[fileName] = true;
            }
        }
        public static void DeleteMedia()
        {
            DeleteSoundbanks(destinationMediaFolder);
            destinationMediaFolder = string.Empty;
        }
        public static void DeleteBuildInMedia()
        {
            DeleteSoundbanks(DefaultBuildInMefiaFolder);
        }

        static void DeleteSoundbanks(string destinationFolder)
        {
            if (string.IsNullOrEmpty(destinationFolder))
                return;
            if (!Directory.Exists(destinationFolder))
            {
                return;
            }

            Directory.Delete(destinationFolder, true);
        }
        #endregion

    }
}
